﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace DJY.Web
{
    public class AjaxValidateAntiForgeryToken : AuthorizeAttribute
    {
        public const string FieldName = "__RequestVerificationToken";

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            if (request.HttpMethod == WebRequestMethods.Http.Post)
            {
                if (request.IsAjaxRequest())
                {
                    var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
                    var cookieValue = antiForgeryCookie?.Value;
                    string formToken = request.Form[FieldName] ?? request.Headers[FieldName];
                    AntiForgery.Validate(cookieValue, formToken);
                }
            }
        }
    }
}